package com.example.hello.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.hello.common.Result;
import com.example.hello.entity.Department;
import com.example.hello.service.DepartmentService;
import com.github.pagehelper.PageInfo;

import jakarta.validation.Valid;

/**
 * 部门控制器
 */
@RestController
@RequestMapping("/departments")
@Validated
public class DepartmentController {
    
    @Autowired
    private DepartmentService departmentService;
    
    /**
     * 数据库连接测试接口
     */
    @GetMapping("/test")
    public Result<String> testConnection() {
        try {
            List<Department> departments = departmentService.getAllDepartments();
            return Result.success("数据库连接正常，查询到 " + departments.size() + " 条记录");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("数据库连接失败：" + e.getMessage() + " - " + e.getClass().getSimpleName());
        }
    }
    
    /**
     * 查询所有部门
     */
    @GetMapping
    public Result<List<Department>> getAllDepartments() {
        try {
            List<Department> departments = departmentService.getAllDepartments();
            return Result.success(departments);
        } catch (Exception e) {
            e.printStackTrace(); // 打印详细错误信息到控制台
            return Result.error("查询部门列表失败：" + e.getMessage() + " - " + e.getClass().getSimpleName());
        }
    }
    
    /**
     * 分页查询部门
     */
    @GetMapping(params = {"page", "pageSize"})
    public Result<Map<String, Object>> getDepartmentsByPage(
            @RequestParam(required = false) String department_name,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            PageInfo<Department> pageInfo = departmentService.getDepartmentsByPage(department_name, page, pageSize);
            
            Map<String, Object> data = new HashMap<>();
            data.put("total", pageInfo.getTotal());
            data.put("rows", pageInfo.getList());
            
            return Result.success(data);
        } catch (Exception e) {
            return Result.error("分页查询部门失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询部门
     */
    @GetMapping("/{id}")
    public Result<Department> getDepartmentById(@PathVariable Integer id) {
        try {
            Department department = departmentService.getDepartmentById(id);
            if (department == null) {
                return Result.error("部门不存在");
            }
            return Result.success(department);
        } catch (Exception e) {
            return Result.error("查询部门失败：" + e.getMessage());
        }
    }
    
    /**
     * 添加部门
     */
    @PostMapping
    public Result<Void> addDepartment(@Valid @RequestBody Department department) {
        try {
            departmentService.addDepartment(department);
            return Result.success();
        } catch (Exception e) {
            return Result.error("添加部门失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新部门
     */
    @PutMapping
    public Result<Void> updateDepartment(@Valid @RequestBody Department department) {
        try {
            departmentService.updateDepartment(department);
            return Result.success();
        } catch (Exception e) {
            return Result.error("更新部门失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除部门
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteDepartment(@PathVariable Integer id) {
        try {
            departmentService.deleteDepartment(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error("删除部门失败：" + e.getMessage());
        }
    }
}
